<template>
    <div class="content">
        <div class="card_header">
            
        </div>

        <div class="card_list">

            <div class="card_header_button">
                <a-button type="primary" @click="visible = true">新增</a-button>
            </div>

            <a-table :columns="columns" :data="data" :loading="loading">
                <template #action="{ record }">
                    <a-button type="text" @click="editCategory(record)">编辑</a-button>
                    <a-button type="text" @click="removeCategory(record.id)">删除</a-button>
                </template>
            </a-table>
        </div>
    </div>

    <a-modal :visible="visible" :title="title" @ok="handleOk(title)" @cancel="visible = false">
        <a-form :model="form" ref="formRef">
            <a-form-item label="名称" name="name">
                <a-input v-model="form.name" placeholder="请输入名称" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { getCategoryList,addCategory,deleteCategory,updateCategory } from '@/api/category';
import { Message,Modal } from '@arco-design/web-vue'
const columns = ref([
    {
        title: '名称',
        dataIndex: 'name',
    },{
        title: '创建时间',
        dataIndex: 'createTime',
    },{
        title: '修改时间',
        dataIndex: 'updateTime',
    },{
        title: '操作',
        slotName: 'action',
        align: 'center'
    }
]);

const loading = ref(false);
const data = ref(null);
const visible = ref(false);
const title = ref('新增分类');
const form = ref({id:null,name:null});

async function getList() {
    loading.value = true;
    const res = await getCategoryList();
    loading.value = false;
    data.value = res.data;
    console.log(data.value);
}

async function handleOk() {
    console.log(form.value);
    if (title.value === '新增分类'){
        let { msg } = await addCategory(form.value);
        Message.success(msg);
    }else{
        let { msg } = await updateCategory(form.value);
        Message.success(msg);
    }
    visible.value = false;
    getList();
}

async function editCategory(record) {
    title.value = '编辑分类';
    form.value.name = record.name;
    form.value.id = record.id;
    console.log(record);
    visible.value = true;
}

async function removeCategory(id){
    Modal.confirm({
        title: '确认删除',
        onOk: async () => {
            let { msg } = await deleteCategory(id);
            Message.success(msg);
            getList();
        }
    });
}

onMounted(() => {
    getList();
});

</script>

<style scoped></style>